package app

import (
	"gitee.com/zmhfly8/gm/global"
	"gitee.com/zmhfly8/gm/pkg/convert"
	"github.com/gin-gonic/gin"
	"math"
	"strconv"
)

type Page struct {
	Page     int
	PageSize int
}

func InitPage(c *gin.Context, p1, ps1 int) Page {
	p := c.Query("page")
	if p == "" && p1 == 0 {
		p = strconv.Itoa(1)
	} else {
		if p1 > 0 {
			p = strconv.Itoa(p1)
		}
	}
	page := convert.StrTo(p).MustInt()
	if page <= 0 {
		page = 1
	}
	ps := c.Query("pageSize")
	if ps == "" && ps1 == 0 {
		ps = strconv.Itoa(global.AppSetting.DefaultPageSize)
	} else {
		if ps1 > 0 {
			ps = strconv.Itoa(ps1)
		}
	}
	pageSize := convert.StrTo(ps).MustInt()
	if pageSize <= 0 {
		pageSize = global.AppSetting.DefaultPageSize
	}
	if pageSize > global.AppSetting.MaxPageSize {
		pageSize = global.AppSetting.MaxPageSize
	}

	return Page{page, pageSize}
}
func GetPage(c *gin.Context) int {
	p := c.Query("page")
	if p == "" {
		return 1
	}
	page := convert.StrTo(p).MustInt()
	if page <= 0 {
		return 1
	}

	return page
}

func GetPageSize(c *gin.Context, maxPageSize int) int {
	p := c.Query("pageSize")
	if p == "" {
		return maxPageSize
	}
	pageSize := convert.StrTo(p).MustInt()
	if pageSize <= 0 {
		return 0
	}
	if pageSize > maxPageSize {
		return maxPageSize
	}

	return pageSize
}

func GetPaging(p Page, total int64) Paging {
	current := p.Page
	limit := p.PageSize
	before := current - 1
	if before < 1 {
		before = 1
	}
	totalPage := int(math.Ceil(float64(total) / float64(limit)))
	if totalPage < 1 {
		totalPage = 1
	}
	next := current + 1
	if next > totalPage {
		next = totalPage
	}

	return Paging{
		First:      1,
		Before:     before,
		Next:       next,
		Current:    current,
		Last:       totalPage,
		Limit:      limit,
		TotalPages: totalPage,
		TotalItems: total,
	}
}
func GetPageOffset(page, pageSize int) int {
	result := 0
	if page > 0 {
		result = (page - 1) * pageSize
	}

	return result
}
